package com.csun.cmny.provider.service.impl;

import com.alibaba.fastjson.JSON;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.core.utils.MD5Util;
import com.csun.cmny.provider.dao.DmcCsunVersionFileMapper;
import com.csun.cmny.provider.device.csun.sleep.SleepMessageGateway;
import com.csun.cmny.provider.device.csun.sleep.entity.MsgSleepUpdateVersion;
import com.csun.cmny.provider.model.constant.DeviceConstant;
import com.csun.cmny.provider.model.domain.DmcCsunVersionFile;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.dto.version.CheckFileVersionDto;
import com.csun.cmny.provider.model.dto.version.CsunVersionQueryDto;
import com.csun.cmny.provider.model.dto.version.SetVersionDto;
import com.csun.cmny.provider.model.vo.csunversion.CsunVersionFileVo;
import com.csun.cmny.provider.model.vo.device.DeviceTypeVo;
import com.csun.cmny.provider.service.DmcCsunVersionFileService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.util.PublicUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-11-20 17:12
 * @Description:
 */
@Slf4j
@Service
@Transactional
public class DmcCsunVersionFileServiceImpl extends BaseService<DmcCsunVersionFile> implements DmcCsunVersionFileService {

    @Resource
    private SleepMessageGateway sleepMessageGateway;
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private DmcCsunVersionFileMapper dmcCsunVersionFileMapper;

    /**
     * 给设备下发版本
     *
     * @param setVersionDto
     * @return
     */
    @Override
    public Integer setVersion(SetVersionDto setVersionDto) {

        String deviceNo = setVersionDto.getDeviceNo();

        List<String> deviceNoList = Arrays.asList(deviceNo.split(","));
        if (PublicUtil.isEmpty(deviceNoList)) {
            log.error("要升级的设备编号不能为空...");
            return null;
        }
        List<DeviceTypeVo> deviceTypeVos = dmcDeviceService.queryDeviceByDeviceNoList(deviceNoList);
        if (PublicUtil.isEmpty(deviceTypeVos)) {
            log.error("要升级的设备不存在...");
            return null;
        }
        if (deviceTypeVos.size() > 1) {
            log.error("每次仅升级一种设备类型...");
            return null;
        }
        DeviceTypeVo deviceTypeVo = deviceTypeVos.get(0);
        log.info("待升级的设备类型 deviceType = {}, typeCode = {}, typeName = {}",
                deviceTypeVo.getDeviceType(), deviceTypeVo.getTypeCode(), deviceTypeVo.getTypeName());

        DmcCsunVersionFile dmcCsunVersionFile = new DmcCsunVersionFile();
        dmcCsunVersionFile.setFileVersion(setVersionDto.getVersion());
        dmcCsunVersionFile.setFileType(deviceTypeVo.getDeviceType());
        dmcCsunVersionFile = dmcCsunVersionFileMapper.selectOne(dmcCsunVersionFile);
        int count = 0;
        if (PublicUtil.isEmpty(dmcCsunVersionFile)) {
            log.error("待升级的版本不存在...");
            return null;
        }

        Integer packLength = DeviceConstant.PACK_LENGTH;
        if (PublicUtil.isNotEmpty(setVersionDto.getPackLength())) {
            packLength = setVersionDto.getPackLength();
        }
        Integer packSize = dmcCsunVersionFile.getFileData().length;
        Integer packCount = packSize / packLength;
        if (packSize % packLength != 0) {
            packCount = packCount + 1;
        }
        String md5 = MD5Util.getMD5String(dmcCsunVersionFile.getFileData());

        // 下发当前版本信息
        MsgSleepUpdateVersion msgSleepUpdateVersion = new MsgSleepUpdateVersion();
        msgSleepUpdateVersion.setMd5(md5);
        msgSleepUpdateVersion.setPackCount(packCount + "");
        msgSleepUpdateVersion.setPackLength(packLength + "");
        msgSleepUpdateVersion.setPackSize(packSize + "");
        msgSleepUpdateVersion.setUpdateVer(setVersionDto.getVersion());


        for (DmcDevice d : deviceTypeVo.getDmcDeviceList()) {

            msgSleepUpdateVersion.setSn(d.getDeviceNo());

            // TODO 更新设备的版本号


            sleepMessageGateway.sendToMqtt(d.getDeviceNo(), 1, JSON.toJSONString(msgSleepUpdateVersion));

            count++;
        }

        return count;
    }

    /**
     * 下载版本
     *
     * @param dmcCsunVersionFile
     *
     * @return
     */
    @Override
    public DmcCsunVersionFile queryCsunVersionFile(DmcCsunVersionFile dmcCsunVersionFile) {

        return dmcCsunVersionFileMapper.queryCsunVersionFile(dmcCsunVersionFile);
    }

    /**
     * query csun version list with page
     *
     * @param csunVersionQueryDto   the csun version query dto
     *
     * @return  the list
     */
    @Override
    public List<CsunVersionFileVo> queryCsunVersionListWithPage(CsunVersionQueryDto csunVersionQueryDto) {

        PageHelper.startPage(csunVersionQueryDto.getPageNum(), csunVersionQueryDto.getPageSize());

        return dmcCsunVersionFileMapper.queryCsunVersionListWithPage(csunVersionQueryDto);
    }

    /**
     * 校验版本编号是否唯一
     *
     * @param checkFileVersionDto the check file version dto
     *
     * @return the boolean
     * true-版本号唯一 false-版本号不唯一
     */
    @Override
    public boolean checkFileVersion(CheckFileVersionDto checkFileVersionDto) {

        Long id = checkFileVersionDto.getId();
        Integer fileType = checkFileVersionDto.getFileType();
        String fileVersion = checkFileVersionDto.getFileVersion();

        Example example = new Example(DmcCsunVersionFile.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("id", id);
        }

        criteria.andEqualTo("fileType", fileType);
        criteria.andEqualTo("fileVersion", fileVersion);

        int result = selectCountByExample(example);

        return result < 1;
    }

    @Test
    public void main() {

        MsgSleepUpdateVersion msgSleepUpdateVersion = new MsgSleepUpdateVersion();
        msgSleepUpdateVersion.setMd5("md5");
        msgSleepUpdateVersion.setPackCount("100");
        msgSleepUpdateVersion.setPackLength("1024");
        msgSleepUpdateVersion.setPackSize("10240");
        msgSleepUpdateVersion.setUpdateVer("0.0.1");
        msgSleepUpdateVersion.setSn("chisj");

        String json = JSON.toJSONString(msgSleepUpdateVersion);

        System.out.println("json = " + json);
    }
}
